const express = require('express');
const multer = require('multer');
const dayjs = require('dayjs')
const path = require('path');
const uploadImgRouter = express.Router();
const { sendResult } = require('../utils/index.js')
const mysql = require('mysql')
const db = mysql.createPool({
    host: "127.0.0.1",
    user: "root",
    password: "admin123",
    database: "mydatabase_01",
    port: 3306,
})


const table = {
    name: 'peoplechange',
}

uploadImgRouter.use(express.json());
uploadImgRouter.use(express.urlencoded({ extended: true }));

// 设置存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/'); // 保存文件的目录
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + path.extname(file.originalname)); // 使用时间戳和文件扩展名来命名文件
    }
});

console.log(dayjs().format('YYYY-MM-DD HH:mm:ss'));

// 初始化 multer 上传
const upload = multer({ storage: storage });

// 创建一个目录来保存上传的文件（如果不存在的话）
const fs = require('fs');
const uploadDir = './uploads';
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir);
}

// 创建一个路由来处理文件上传
uploadImgRouter.post('/upload', upload.single('image'), (req, res) => {
    try {
        // 获取文件信息
        const file = req.file;
        if (!file) {
            return res.status(400).json({ message: 'Please upload a file' });
        }

        // 构建图片链接（这里假设你的服务器运行在 localhost:3000）
        const imageUrl = `http://localhost:3001/uploads/${file.filename}`;

        // 返回图片链接
        res.json({ message: 'File uploaded successfully', imageUrl: imageUrl });
    } catch (error) {
        res.status(500).json({ message: 'Error uploading file', error: error.message });
    }
});


module.exports = uploadImgRouter;